import editForm from "../form.vue";
// import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
// import {getMenuList, getPurchaseUserList} from "@/api/system";
import { 
  getAdAccountList, 
  createAdAccount, 
  updateAdAccount, 
  deleteAdAccount,
  exportAdAccount,
  getAdAgentOptions
} from "@/api/ads";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps, AgentOption, PaginatedResponse } from "../utils/types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { cloneDeep, deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { ElMessageBox } from "element-plus";
import { getPlatformInfo } from "./ad-account";


export function useAdAccount() {
  const form = reactive({
    account_no: "",
    ad_agent_id: "",
    keyword: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const agentOptions = ref<AgentOption[]>([]);
  const selectedRows = ref([]);
  
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,
    pageSizes: [15, 30, 50, 100],
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left"
    },
    {
      label: "账号",
      prop: "account_no",
      align: "left",
      minWidth: 180
    },
    {
      label: "代理商",
      prop: "agent_name",
      align: "left",
      minWidth: 150,
      cellRenderer: ({ row }) => {
        const agent = agentOptions.value.find(a => a.value === row.ad_agent_id);
        if (agent) {
          const agentName = agent.label.split(' (')[0];
          return agentName;
        }
        return "-";
      }
    },
    {
      label: "平台",
      prop: "platform",
      width: 100,
      cellRenderer: ({ row }) => {
        const agent = agentOptions.value.find(a => a.value === row.ad_agent_id);
        if (!agent) return "-";
        
        return (
          <el-tag
            type={getPlatformInfo(agent.platform, 'type')}
            effect="plain"
          >
            {agent.platform_text}
          </el-tag>
        );
      }
    },
    {
      label: "创建者",
      prop: "creator_name",
      align: "left",
      minWidth: 120,
      showOverflowTooltip: true
    },
    {
      label: "备注",
      prop: "remark",
      align: "left",
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      label: "创建时间",
      prop: "created_at",
      minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    selectedRows.value = val;
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    try {
      const params = {
        page: pagination.currentPage,
        size: pagination.pageSize,
        account_no: form.account_no,
        ad_agent_id: form.ad_agent_id,
        keyword: form.keyword
      };

      const { data } = await getAdAccountList(params);
      
      dataList.value = data.data || [];
      pagination.total = data.total || 0;
      pagination.currentPage = data.current_page || 1;
      pagination.pageSize = data.per_page || 15;
      
    } catch (error) {
      console.error("获取数据失败:", error);
      message("获取数据失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  async function loadAgentOptions() {
    try {
      const { data } = await getAdAgentOptions();
      agentOptions.value = data || [];
    } catch (error) {
      console.error("获取代理商选项失败:", error);
    }
  }

  function chores(curData: FormItemProps, res: any, title: string, done?: (() => void)) {
    message(`您${title}了账号为${curData.account_no}的这条数据`, {
      type: "success"
    });
    if (done) done();
    onSearch();
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}广告账号`,
      props: {
        formInline: {
          account_no: row?.account_no ?? "",
          ad_agent_id: row?.ad_agent_id,
          remark: row?.remark ?? "",
          agentOptions: agentOptions.value
        }
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { 
        ref: formRef,
        formInline: {
          account_no: row?.account_no ?? "",
          ad_agent_id: row?.ad_agent_id,
          remark: row?.remark ?? "",
          agentOptions: agentOptions.value
        }
      }),
      beforeSure: (done: () => void) => {
        const FormRef = formRef.value.getRef();
        
        FormRef.validate(async (valid: boolean) => {
          if (valid) {
            try {
              // 从表单组件中获取用户输入的数据
              const formData = formRef.value.getFormData();
              const curData = {
                account_no: formData.account_no,
                ad_agent_id: formData.ad_agent_id,
                remark: formData.remark,
                id: row?.id // 更新时需要ID
              } as FormItemProps;
              
              let res;
              if (title === "新增") {
                res = await createAdAccount(curData);
              } else {
                res = await updateAdAccount(curData);
              }
              chores(curData, res, title, done);
            } catch (error) {
              message(`${title}失败`, { type: "error" });
            }
          }
        });
      }
    });
  }

  async function handleDelete(row?: FormItemProps) {
    const ids = row ? [row.id] : selectedRows.value.map(item => item.id);
    const accountNames = row ? [row.account_no] : selectedRows.value.map(item => item.account_no);
    
    if (!ids.length) {
      message("请选择要删除的数据", { type: "warning" });
      return;
    }

    try {
      await ElMessageBox.confirm(
        `确认删除账号：${accountNames.join("、")} 吗？`,
        "删除确认",
        {
          type: "warning"
        }
      );

      const res = await deleteAdAccount({ id: ids.join(",") });
      message(`成功删除${ids.length}个广告账号`, { type: "success" });
      onSearch();
    } catch (error) {
      if (error !== "cancel") {
        message("删除失败", { type: "error" });
      }
    }
  }

  async function handleExport() {
    try {
      const params = {
        account_no: form.account_no,
        ad_agent_id: form.ad_agent_id,
        keyword: form.keyword
      };

      const res = await exportAdAccount(params);
      const blob = new Blob([res], { 
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 
      });
      
      const fileName = `广告账号数据_${new Date().toLocaleDateString()}.xlsx`;
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message("导出成功", { type: "success" });
    } catch (error) {
      message("导出失败", { type: "error" });
    }
  }

  onMounted(async () => {
    await loadAgentOptions();
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedRows,
    agentOptions,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleExport,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
